%------------------------------------------------------------------
%------------------------------------------------------------------
%   Author: Md. Sazzad Hussain (sazzad.hussain@sydney.edu.au)
%   Learning and Affect Technologies Engineering (LATTE)
%   University of Sydney, 2012
%------------------------------------------------------------------
%------------------------------------------------------------------

function [x] = edr(indir,outdir,subjectID,opSys)

if opSys==1;
    sep='/';
elseif opSys==2
    sep='\'
end

filesPath=indir;
filesDir=dir(filesPath);%dir info for files path
x=1;
for m=1:length(filesDir)
    [path,name,ext,ver] = fileparts(filesDir(m).name);
    for n=1:length(subjectID(:,1))
        if strncmp(subjectID(n,:),name,27)%choose only selected subjects
            if strcmp(ext,'.mat')%.mat files
                loadPhysio(x,:)=[filesPath sep name ext];%.mat physio path
                physioSplit(x,:)= regexp(name,'_','split');
                x=x+1;
            end
        end
    end
end

mkdir(outdir);%create directory for features (.mat)
for j=1:(x-1)
    load(loadPhysio(j,:));%load physio file
    ecgData=data(:,1);

    % % derive respiration from ECG signal
    endP=length(ecgData);

    a=ecgData;
    lent =8;
    stantlent =9;
    stanfmax=200;

    % currf=input('what is the current sampling rate :');
    currf=1024;

    if (stanfmax>currf)
        p=stanfmax/currf;
        if (rem(stanfmax,currf)~=0)
            p=round(p)-1;
        end
        n=factor(p);
        x=length(n);
        lent=9-x;
    else 
        if(stanfmax==currf)
            lent=9;
        else
            p=currf/stanfmax;
            if (rem(currf,stanfmax)~=0)
                p=round(p)-1;
            end
            n=factor(p);
            x=length(n);
            lent=9+x;
        end
    end

    % % carry out Nth level decomposition using wavelet transform 
    [c,l]=wavedec(a,lent,'db4');
    la9=l(1);
    ld9=l(2);
    len=length(c);

    % % to reconstruct the detail signal fo the nth level of decomposition
    for i=1:len
        if ((i<la9)|(i>la9+ld9+1))
            c(i)=0;
        end
    end

    x=waverec(c,l,'db4');
    x=x./max(x);
    x=x([1:endP],:);
    edResp=x;    
    
    matFile=[outdir, sep, subjectID(j,:),'.mat'];
    save(matFile,'edResp');
    clear ecgData edResp;
    
%     subplot(2,1,1);
%     plot(ecgData(40000:50000));
%     title('ECG Signal');
% 
%     subplot(2,1,2);
%     plot(x(40000:50000));
%     title('Derived Respiration Signal');

%     [p,f]=psd(x, 256,1024);
%     % mean:
%     mpf
%     bpm=mpf*60

end
clear all;
x=1;